package com.lyc.ssm.action;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

@Controller
public class DownloadController {

    @RequestMapping("/view")
    public String view() {
        return "download";
    }

    @RequestMapping(value = "/undownload", method = RequestMethod.GET)
    public ResponseEntity<byte[]> undownload(HttpServletRequest request) throws IOException {
        String path = request.getServletContext().getRealPath("/WEB-INF/download");
        File file = new File(path + "/file.xlsx");
//        System.out.println(ids.toString());
        System.out.println(file.getPath());
        System.out.println(file.getName());
        //创建响应头
        HttpHeaders headers = new HttpHeaders();
        //添加附件并设置其名称
        headers.set("Content-Disposition", "attachment;fileName=" + file.getName());
        //设置附件格式 自动识别
//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return ResponseEntity.ok().headers(headers).contentType(MediaType.MULTIPART_FORM_DATA).body(FileUtils.readFileToByteArray(file));
    }

    @RequestMapping(value = "/download", method = RequestMethod.POST)
    @ResponseBody
    public String download() {
        //发送OKHttp请求
        return "http://localhost:8080/undownload";
    }
}
